package viqiang.ye.mallpuny.service.impl;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import viqiang.ye.mallpuny.dao.EsProductDao;
import viqiang.ye.mallpuny.nosql.elasticsearch.document.EsProduct;
import viqiang.ye.mallpuny.nosql.elasticsearch.document.repository.EsProductRepository;
import viqiang.ye.mallpuny.service.EsProductService;

import java.util.Iterator;
import java.util.List;

@Service
public class EsProductServiceImpl implements EsProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(EsProductServiceImpl.class);
    @Autowired
    private EsProductDao productDao;
    @Autowired
    private EsProductRepository productRepository;


    @Override
    public int importAll() {
        List<EsProduct> esProductList = productDao.getAllEsProductList(null);
        Iterable<EsProduct> esProductIterable = productRepository.saveAll(esProductList);
        Iterator<EsProduct> iterator = esProductIterable.iterator();
        int result = 0;
        while (iterator.hasNext()) {
            result++;
            iterator.next();
        }
        return result;
    }

    @Override
    public void delete(Long id) {
        productRepository.deleteById(id);
    }

    @Override
    public EsProduct create(Long id) {
        EsProduct esProduct = null;
        List<EsProduct> esProductList = productDao.getAllEsProductList(id);
        if (esProductList != null && esProductList.size() > 0) {
            esProduct = productRepository.save(esProductList.get(0));
        }
        return esProduct;
    }

    @Override
    public void delete(List<Long> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            List<EsProduct> esProducts = Lists.newArrayList();
            ids.stream().forEach(i -> {
                EsProduct product = new EsProduct();
                product.setId(i);
                esProducts.add(product);
            });
            productRepository.deleteAll(esProducts);
        }
    }

    @Override
    public Page<EsProduct> search(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return productRepository.findByNameOrSubTitleOrKeywords(keyword,keyword,keyword,pageable);
    }
}
